package exp3;
import com.sun.mail.imap.IMAPFolder;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.servlet.http.Part;
import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import java.util.Map;


@WebServlet(urlPatterns = {"/upload"})
@MultipartConfig(location = "C:\\Users\\Aiden\\Desktop\\shiyanone\\src\\main\\webapp\\image")
public class post_photo_exp3  extends HttpServlet {
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        try {
            request.setCharacterEncoding("UTF-8");
            response.setContentType("text/html;charset=UTF-8");
            //Map<String ,String> username=(Map<String, String>)request.getSession().getAttribute("name");
            // 获取请求项，封装成Part对象
            // request.getPart方法的传参为前端页面from表单的input文件组件的name值
            Part part = request.getPart("file");

            // part.getSubmittedFileName()方法获取上传文件的文件名
            // String fileName = part.getSubmittedFileName();

            HttpSession session;
            session = request.getSession();
            userdata user = (userdata) session.getAttribute("user");
            String fileName = user.getUsername() + ".jpg";
            user.setPath("../image/"+fileName);
            String filepath = user.getPath();
            File uploadedFile = new File("C:\\Users\\Aiden\\Desktop\\shiyanone\\src\\main\\webapp\\image\\"+filepath, fileName);
            System.out.println("上传文件的文件名: " + fileName);
            System.out.println(filepath);
            if (uploadedFile.exists()){ uploadedFile.delete();}
            // 根据@MultipartConfig的location配置的目录上传文件，直接传参文件名即可。
            part.write(fileName);

            response.sendRedirect("/dispay_exp3.jsp");
        }catch (Exception e)
        {
            e.printStackTrace();
        }
    }
}
